/* Copyright 203-2115 AtomWare Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * The flowing information must be keep 
 * DetailsFilter.java
 * testProjects
 * 2013-7-11上午11:43:29
 * @author 屈甲康
 * QQ285799123
 * mailto:qujiakang@gmail.com
 */

package org.jackysoft.test;

import java.io.IOException;
import java.security.Principal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DetailsFilter implements Filter {

	
	private Map<String,Map<String,Set<String>>> cache = new HashMap<String,Map<String,Set<String>>>();
	@Override
	public void destroy() {
		

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		
		HttpServletRequest  request  = (HttpServletRequest) arg0;
			
		HttpServletResponse response = (HttpServletResponse) arg1;
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath() + "/index.jsp";
		Principal  princ = request.getUserPrincipal();
		if(princ==null)
	        response.sendRedirect(basePath);
		else{
			
		    String name = princ.getName();
		    Map<String,Set<String>> tmps = cache.get(name);
		    Map<String,Set<String>> userrole = new HashMap<String,Set<String>>();
		    userrole.putAll(tmps);
		    request.getSession().setAttribute("loginuser", userrole);
		    System.out.println(name+" has  logined!");
		}
		arg2.doFilter(arg0, arg1);

	}
	
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		Connection conn = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://128.10.40.5/statbak2?autoReconnect=true", "root", "7536987412");
			PreparedStatement  stat3 = conn.prepareStatement(
					" select su.name uname,localName,ifnull(d.parent_id,d.id) as 'did',ua.authority_id auname"+
					" from sysuser su"+
					" join department d on d.id = su.department_id"+
					" join user_authority ua on ua.user_id=su.name");
		    ResultSet    rst3  = stat3.executeQuery();
		    
		    while(rst3.next()){    	
		    	
		    	final String uname = rst3.getString("uname");
		    	final String zname = rst3.getString("localName");
		    	final String did   = rst3.getString("did");
		    	final String aname = rst3.getString("auname");
		    	Map<String,Set<String>> userrole = cache.get(uname);
		    	if(userrole==null){
		    		userrole = new HashMap<String,Set<String>>();
		    		cache.put(uname, userrole);
		    	}
		    	
		    	userrole.put("zname", new HashSet<String>(){	    		
					private static final long serialVersionUID = 4391990934773085662L;
					{
		    			add(zname);
		    		}
		    	});
		    	
		    	userrole.put("dept",new HashSet<String>(){static final long serialVersionUID = 8917288349351703720L;{add(did);}});
		    	
		    	Set<String> roleset = userrole.get("role");
			    if(roleset==null){
			    	roleset = new HashSet<String>();
			    	userrole.put("role", roleset);
			    }
			    roleset.add(aname);  
			  
		    }		   
		    	   
		    stat3.close();
		    System.out.println(cache);
		
		} catch (ClassNotFoundException | SQLException e) {
			//logger.error(e);
			e.printStackTrace();
		} finally{
			if(conn!=null)
				try {
					conn.close();
				} catch (SQLException e) {
					//logger.error(e);
					e.printStackTrace();
				}
		}
		
	}

}
